package com.smart.sso.demo.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.net.URL;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import com.para.esc.web.common.APIUtil;

@Controller
@Slf4j
@RequestMapping("/")
public class LoginController {
    public static void main(String[] args) {
        String token = APIUtil.getAccessTokenParam("ST-9735-gegLS3DmeeJ1zHcb1XDH");
        JSONObject jb = JSONObject.fromObject(token);
        String access_token = jb.getString("access_token");
        System.out.println("token--------------" + access_token);
        String result = APIUtil.getUserParam(access_token);
        log.info("--------------result-------------" + result);

    }

    @RequestMapping(value = {"to"})
    public void login(HttpServletResponse response) {
        String result = null;
        try {
            result = APIUtil.xTJC();
//			System.out.println(result);
            if (result.equals("OK")) {
                String url = APIUtil.SSORequest();
                try {
                    response.sendRedirect(url);//重定向地址
                } catch (IOException e) {
                    System.out.println("SSO请求地址失败" + e);
                }

            } else {
                System.out.println("心跳检测失败");
            }
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    /**
     * 第二步，OAuth的回调地址<p>
     * 用户在IAM的登录页面认证通过之后，IAM会重定向回该地址，把code传递回来
     */
//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		// 获取code
//		String code = request.getParameter("code");
//		System.out.println("code:"+code);
//		// 获取认证成功后，跳转到的目标地址。比如用户登录成功后，需要跳转到应用系统的某个特定页面，而不是应用系统默认的首页。
//		String target_uri = request.getParameter("target_uri");
//
//		Properties p = ResourceProp.getboProperties();
//		String oauthurl = p.getProperty("oauthurl");
//		System.out.println("oauthurl:"+oauthurl);
//		try {
//			String token = APIUtil.getAccessTokenParam(code);
//			JSONObject jb = JSONObject.fromObject(token);
//			String status = jb.getString("status");
//			if(!status.equals("200")){
//				System.out.println("获取token失败");
//				return;
//			}
//			//解析token
//			String token = jb.getString("access_token");
//
//
//
//
//			System.out.println("token:"+token);
//			if(token.equals("")||token.equals("null")||token.indexOf("失败")!=-1){
//				response.sendRedirect(oauthurl+"/oauth_error.jsp?message=1");
//				return ;
//			}
//
//			// 执行第四步，用token去换取用户信息
//			String ssoprofile = p.getProperty("ssoprofile");
//
//			String uidJson = getResult(ssoprofile,token);
//			System.out.println("ssoprofile:"+ssoprofile);
//			System.out.println("uidJson:"+uidJson);
//			if(uidJson.equals("")||uidJson.equals("null")){
//				response.sendRedirect(oauthurl+"/oauth_error.jsp?message=2");
//				return;
//			}
//
//			// 解析json格式的用户信息
//			JSONObject user = JSONObject.fromObject(uidJson);
//			String uid = user.getString("id");
////			String uid = "D010844";
//			// 将用户信息存放到session中。应用系统当做用户登录成功。
//			request.getSession().setAttribute("uid", uid.toUpperCase());
//			request.getSession().setAttribute("user", uid.toUpperCase());
//			System.out.println("uid:"+uid);
//			if(target_uri != null && !"".equals(target_uri.trim())) {
//				response.sendRedirect(target_uri); // 如果指定了认证后跳转的页面
//			}else {
//				request.getRequestDispatcher("/").forward(request, response); // 如果没有指定认证后的跳转页面，
//			}
//		}
//		catch (Exception e) {
//			e.printStackTrace();
//			response.sendRedirect(request.getContextPath()+"/oauth_error.jsp");
//			return ;
//		}
//	}
    @RequestMapping(value = {"back"})
    public void callback(
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        // 获取code
        String code = request.getParameter("code");

        log.info("-----------------------code------------------" + code);

        String token = APIUtil.getAccessTokenParam(code);
        log.info("---------------token------------------------" + token);
        /*JSONObject jb = JSONObject.fromObject(token);
        String status = jb.getString("status");
        if (!status.equals("200")) {
            System.out.println("获取token失败");
            return;
        }
        //解析token
        String access_token = jb.getString("access_token");

        log.info("---------------accesstoken------------------------" + access_token);*/
        /*String result = APIUtil.getUserParam(access_token);
        JSONObject useparams = JSONObject.fromObject(result);
        log.info("------------useparams-----------------------" + useparams.toString());
        status = useparams.getString("status");
        if (!status.equals("200")) {
            System.out.println("获取token失败");
            return;
        }
        //解析用户信息
        String uid = useparams.getString("id");

        request.getSession().setAttribute("uid", uid.toUpperCase());
        request.getSession().setAttribute("user", uid.toUpperCase());
        System.out.println("uid:" + uid);

        // 获取认证成功后，跳转到的目标地址。比如用户登录成功后，需要跳转到应用系统的某个特定页面，而不是应用系统默认的首页。
        String target_uri = request.getParameter("target_uri");
        log.info("---------target_uri-----------------" + target_uri);

        try {
            if (target_uri != null && !"".equals(target_uri.trim())) {
                response.sendRedirect(target_uri); // 如果指定了认证后跳转的页面
            } else {
                response.sendRedirect("http//:10.0.0.102:8084"); // 如果没有指定认证后的跳转页面，
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

    }

	@RequestMapping(value = {"back1"})
	public void callback1(
			HttpServletRequest request, HttpServletResponse response) {

		// 获取code
		String code = request.getParameter("code");

		log.info("-----------------------code1------------------" + code);
		String token = APIUtil.getAccessTokenParam(code);
		log.info("---------------token------------------------" + token);
        /*JSONObject jb = JSONObject.fromObject(token);
        String status = jb.getString("status");
        if (!status.equals("200")) {
            System.out.println("获取token失败");
            return;
        }
        //解析token
        String access_token = jb.getString("access_token");

        log.info("---------------accesstoken------------------------" + access_token);*/
        /*String result = APIUtil.getUserParam(access_token);
        JSONObject useparams = JSONObject.fromObject(result);
        log.info("------------useparams-----------------------" + useparams.toString());
        status = useparams.getString("status");
        if (!status.equals("200")) {
            System.out.println("获取token失败");
            return;
        }
        //解析用户信息
        String uid = useparams.getString("id");

        request.getSession().setAttribute("uid", uid.toUpperCase());
        request.getSession().setAttribute("user", uid.toUpperCase());
        System.out.println("uid:" + uid);

        // 获取认证成功后，跳转到的目标地址。比如用户登录成功后，需要跳转到应用系统的某个特定页面，而不是应用系统默认的首页。
        String target_uri = request.getParameter("target_uri");
        log.info("---------target_uri-----------------" + target_uri);

        try {
            if (target_uri != null && !"".equals(target_uri.trim())) {
                response.sendRedirect(target_uri); // 如果指定了认证后跳转的页面
            } else {
                response.sendRedirect("http//:10.0.0.102:8084"); // 如果没有指定认证后的跳转页面，
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

	}

}
